package com.syni.mdd.yhd.common.all.service.impl.groupBuy;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.groupBuy.BmsUserBargainDao;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.bargain.BargainActionRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.bargain.BargainHelpPageRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.bargain.BargainRecordRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.bargain.PersonBargainRecordRpDto;
import com.syni.mdd.yhd.common.all.entity.BmsBusiness;
import com.syni.mdd.yhd.common.all.entity.BmsDxGroupBuy;
import com.syni.mdd.yhd.common.all.entity.BmsDxOrder;
import com.syni.mdd.yhd.common.all.entity.groupBuy.BmsUserBargain;
import com.syni.mdd.yhd.common.all.entity.groupBuy.BmsUserHelpBargain;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.enums.groupBuy.BargainGroupBuyEnums;
import com.syni.mdd.yhd.common.all.listen.groupBuy.bargain.GroupBuyBargainEvent;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.activity.BmsBackCardService;
import com.syni.mdd.yhd.common.all.service.groupBuy.BmsUserBargainService;
import com.syni.mdd.yhd.common.all.service.groupBuy.BmsUserHelpBargainService;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.sjb.common.component.utils.common.utils.ArithUtil;
import com.syni.mdd.yhd.common.all.utils.RestTemplateUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @className
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
public class BmsUserBargainServiceImpl extends BaseService<BmsUserBargain,Integer> implements BmsUserBargainService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    BmsUserBargainDao bmsUserBargainDao;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Autowired
    BmsUserHelpBargainService bmsUserHelpBargainService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsBackCardService bmsBackCardService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Override
    public BmsUserBargainDao getBaseDao() {
        return bmsUserBargainDao;
    }

    @Override
    public BmsUserBargain getBargainById(Integer bargainId) {
        Optional<BmsUserBargain> bmsUserBargain = bmsUserBargainDao.findById(bargainId);
        if(bmsUserBargain.isPresent()){
            return bmsUserBargain.get();
        }
        return null;
    }

    @Override
    @Transactional
    public Map<String, Object> bargain(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer groupBuyId = paramsMap.getInteger("groupBuyId");
        Date nowTime = new Date();
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyService.getGroupBuyById(groupBuyId);
        if(bmsDxGroupBuy == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY,ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
        }
        //是否已经发起过砍价了
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("groupBuyId",groupBuyId);
        conditionMap.put("newTime_LTTE",nowTime);
        conditionMap.put("overTime_GTT",nowTime);
        BmsUserBargain bmsUserBargain = null;
        Double cutPrice;
        List<BmsUserBargain> bmsUserBargains = bmsUserBargainDao.findAll(new SpecificationUtils(conditionMap));
        if(bmsUserBargains != null && bmsUserBargains.size() > 0){
            bmsUserBargain = bmsUserBargains.get(0);
            if(bmsUserBargain.getProState() != CAN_BARGAIN_STATUS){
                return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_ALREADY_OVER);
            }
            final String NO_HAVA_BARGAIN_CHANCE = "-9";
            Map<String,Object> retMap = startBargain(bmsUserBargain.getUserId(),bmsUserBargain.getSaasOrderId());
            log.info("saas返回的数据：" + JSON.toJSONString(retMap));
            if(!(retMap.containsKey("status") && (ResultCode.CODE_NORMAL.equals(retMap.get("status").toString())))){
                if(retMap.containsKey("status") && NO_HAVA_BARGAIN_CHANCE.equals(retMap.get("status").toString())){
                    return ResultMapHelper.result("-3","您已对该商品发起砍价，请勿重复发起");
                }
                return retMap;
            }
            Map<String,Object> resultData = (Map<String, Object>) retMap.get("data");
            cutPrice = Double.parseDouble(resultData.get("cutPrice").toString());
            Double startPrice = Double.parseDouble(resultData.get("startPrice").toString());
            Double nowPrice = Double.parseDouble(resultData.get("nowPrice").toString());
            String endTime = resultData.get("endTime").toString();
            String expireTime = resultData.get("expireTime").toString();
            bmsUserBargain.setStartPrice(startPrice);
            bmsUserBargain.setFinallyPrice(nowPrice);
            bmsUserBargain.setOverTime(DateTimeUtils.converStringToDate(endTime, DateTimeUtils.DATE_PATTERN_TIMESTAMP));
            bmsUserBargain.setExpireTime(DateTimeUtils.converStringToDate(expireTime,DateTimeUtils.DATE_PATTERN_TIMESTAMP));
        }else {
            //创建砍价订单并且砍价
            Map<String,Object> retMap = this.createUserBargain(userId,bmsDxGroupBuy.getBargainId());
            log.info("saas返回的数据：" + JSON.toJSONString(retMap));
            if(!(retMap.containsKey("status") && (ResultCode.CODE_NORMAL.equals(retMap.get("status").toString())))){
                return retMap;
            }
            Map<String,Object> resultData = (Map<String, Object>) retMap.get("data");
            String orderId = resultData.get("orderId").toString();
            cutPrice = Double.parseDouble(resultData.get("cutPrice").toString());
            Double startPrice = Double.parseDouble(resultData.get("startPrice").toString());
            Double nowPrice = Double.parseDouble(resultData.get("nowPrice").toString());
            String endTime = resultData.get("endTime").toString();
            String expireTime = resultData.get("expireTime").toString();
            bmsUserBargain = new BmsUserBargain();
            bmsUserBargain.setGroupBuyId(groupBuyId);
            bmsUserBargain.setUserId(userId);
            bmsUserBargain.setNewTime(nowTime);
            bmsUserBargain.setSaasOrderId(orderId);
            bmsUserBargain.setStartPrice(startPrice);
            bmsUserBargain.setFinallyPrice(nowPrice);
            bmsUserBargain.setBusinessId(bmsDxGroupBuy.getBusinessId());
            bmsUserBargain.setOverTime(DateTimeUtils.converStringToDate(endTime,DateTimeUtils.DATE_PATTERN_TIMESTAMP));
            bmsUserBargain.setExpireTime(DateTimeUtils.converStringToDate(expireTime,DateTimeUtils.DATE_PATTERN_TIMESTAMP));
        }
        if(DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsUserBargain.getOverTime())
                && DateTimeUtils.converDateToInterger(nowTime) < DateTimeUtils.converDateToInterger(bmsUserBargain.getExpireTime())){
            bmsUserBargain.setProState(CAN_BUY_STATUS);
        }else if(DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsUserBargain.getExpireTime())){
            bmsUserBargain.setProState(EXPIRE_STATUS);
        }
        bmsUserBargainDao.save(bmsUserBargain);
        //创建砍价订单并且砍价
        /*Map<String,Object> retMap = this.createUserBargain(userId,bmsDxGroupBuy.getBargainId());
        log.info("saas返回的数据：" + JSON.toJSONString(retMap));
        if(!(retMap.containsKey("status") && (ResultCode.CODE_NORMAL.equals(retMap.get("status").toString())))){
            return retMap;
        }
        Map<String,Object> resultData = (Map<String, Object>) retMap.get("data");
        String orderId = resultData.get("orderId").toString();
        Double cutPrice = Double.parseDouble(resultData.get("cutPrice").toString());
        Double startPrice = Double.parseDouble(resultData.get("startPrice").toString());
        Double nowPrice = Double.parseDouble(resultData.get("nowPrice").toString());
        String endTime = resultData.get("endTime").toString();
        String expireTime = resultData.get("expireTime").toString();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("groupBuyId",groupBuyId);
        conditionMap.put("saasOrderId",orderId);
        List<BmsUserBargain> bmsUserBargains = bmsUserBargainDao.findAll(new SpecificationUtils(conditionMap));
        BmsUserBargain bmsUserBargain = null;
        if(!(bmsUserBargains != null && bmsUserBargains.size() > 0)){
            bmsUserBargain = new BmsUserBargain();
            bmsUserBargain.setGroupBuyId(groupBuyId);
            bmsUserBargain.setUserId(userId);
            bmsUserBargain.setNewTime(nowTime);
            bmsUserBargain.setSaasOrderId(orderId);
            bmsUserBargain.setStartPrice(startPrice);
            bmsUserBargain.setFinallyPrice(nowPrice);
            bmsUserBargain.setBusinessId(bmsDxGroupBuy.getBusinessId());
            bmsUserBargain.setOverTime(DateTimeUtils.converStringToDate(endTime,DateTimeUtils.DATE_PATTERN_TIMESTAMP));
            bmsUserBargain.setExpireTime(DateTimeUtils.converStringToDate(expireTime,DateTimeUtils.DATE_PATTERN_TIMESTAMP));
        }else {
            bmsUserBargain = bmsUserBargains.get(0);
        }
        bmsUserBargainDao.save(bmsUserBargain);
        BargainActionRpDto bargainActionRpDto = new BargainActionRpDto();
        bargainActionRpDto.setBargainId(bmsUserBargain.getId());
        bargainActionRpDto.setBargainPrice(Double.parseDouble(resultData.get("cutPrice").toString()));
        bargainActionRpDto.setOverTime(bmsUserBargain.getOverTime());
        bargainActionRpDto.setServerTime(nowTime);*/
        //同步插入一条砍价记录
        bmsUserHelpBargainService.addBargainRecord(userId,bmsUserBargain.getId(),cutPrice);
        BmsCommonService.getApplicationContext().publishEvent(new GroupBuyBargainEvent("countBargainNum",bmsUserBargain));
        //封装数据
        BargainActionRpDto bargainActionRpDto = new BargainActionRpDto();
        bargainActionRpDto.setBargainId(bmsUserBargain.getId());
        bargainActionRpDto.setBargainPrice(cutPrice);
        bargainActionRpDto.setOverTime(bmsUserBargain.getOverTime());
        bargainActionRpDto.setServerTime(nowTime);
        bargainActionRpDto.setFinallyPrice(bmsUserBargain.getFinallyPrice());
        //bargainActionRpDto.setBmsUserHelpBargains(bmsUserHelpBargainService.get);
        return ResultMapHelper.success(bargainActionRpDto,ResultMsg.HAND_SUCCESS);
    }

    private Map<String,Object> startBargain(Integer userId,String bargainId) {
        Map<String,Object> retMap = new HashMap<>();
        retMap.put("status",ResultCode.CODE_ERROR);
        retMap.put("msg",ResultMsg.HAND_FAIL);
        retMap.put("data",null);
        final String OLD_USER = "0";
        final String NEW_USER = "1";
        String isNew = NEW_USER;
        if(checkUserIsStartBargain(userId)){
            isNew = OLD_USER;
        }
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("userId",userId);
        paramsMap.put("isNew",isNew);
        Map<String,Object> headerData = new HashMap<>();
        headerData.put("token",bargainId);
        String url = AppConfig.getProperty("saasGroupBuySys") + startCuttingOrderUrl;
        String responseBody = RestTemplateUtils.postForEntityForJson(url, HttpMethod.POST,headerData,paramsMap);
        if(StringUtils.isNotBlank(responseBody)){
            retMap = JSON.parseObject(responseBody);
        }
        return retMap;
    }

    private boolean checkUserIsStartBargain(Integer userId) {
        List<BmsUserHelpBargain> bmsUserHelpBargains = bmsUserHelpBargainService.findUserHelpRecord(userId);
        if(bmsUserHelpBargains != null && bmsUserHelpBargains.size() > 0){
            return true;
        }
        return false;
    }

    private Map<String,Object> createUserBargain(Integer userId,String bargainId) {
        Map<String,Object> retMap = new HashMap<>();
        retMap.put("status",ResultCode.CODE_ERROR);
        retMap.put("msg",ResultMsg.HAND_FAIL);
        retMap.put("data",null);
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("userId",userId);
        paramsMap.put("bargainId",bargainId);
        log.info("创建砍价订单的参数：" + JSON.toJSONString(paramsMap));
        String url = AppConfig.getProperty("saasGroupBuySys") + createCuttingOrderUrl;
        String responseBody = RestTemplateUtils.postForEntityForJson(url,paramsMap);
        if(StringUtils.isNotBlank(responseBody)){
            retMap = JSON.parseObject(responseBody);
        }
        return retMap;
    }

    @Override
    public Map<String, Object> getMyBargain(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer bargainId = paramsMap.getInteger("bargainId");
        Optional<BmsUserBargain> bmsUserBargainOptional = bmsUserBargainDao.findById(bargainId);
        if(!bmsUserBargainOptional.isPresent()){
            return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_NO_EXIST);
        }
        BmsUserBargain bmsUserBargain = bmsUserBargainOptional.get();
        BargainRecordRpDto bargainRecordRpDto = new BargainRecordRpDto();
        List<BmsUserHelpBargain> helpBargainPage = bmsUserHelpBargainService.getHelpRecord(bmsUserBargain.getId());
        BeanUtils.copyProperties(bmsUserBargain,bargainRecordRpDto.getBmsUserBargain());
        bargainRecordRpDto.setUserHelpBargainList(helpBargainPage);
        bargainRecordRpDto.getBmsUserBargain().setAlreadyBargainMoney(ArithUtil.sub(bmsUserBargain.getStartPrice(),bmsUserBargain.getFinallyPrice()));
        return ResultMapHelper.success(bargainRecordRpDto,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> helpBargainPage(ParamsMap paramsMap) {
        //Integer userId = paramsMap.getInteger("userIdentify");
        Integer bargainId = paramsMap.getInteger("bargainId");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Optional<BmsUserBargain> bmsUserBargainOption = bmsUserBargainDao.findById(bargainId);
        if(!bmsUserBargainOption.isPresent()){
            return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_NO_EXIST);
        }
        BmsUserBargain bmsUserBargain = bmsUserBargainOption.get();
        Page<BmsUserHelpBargain> helpBargainPage = bmsUserHelpBargainService.getHelpRecord(bargainId,1,pageSize);
        List<BmsUserHelpBargain> helpBargains = helpBargainPage.getContent();
        BargainHelpPageRpDto bargainHelpPageRpDto = new BargainHelpPageRpDto();
        BmsUser bmsUser = TokenManager.getUser(bmsUserBargain.getUserId());
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,ResultMsg.CODE_USER_NO_EXIST);
        }
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyService.getGroupBuyById(bmsUserBargain.getGroupBuyId());
        if(bmsDxGroupBuy == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY,ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
        }
        BmsBusiness bmsBusiness = bmsBusinessService.getBusinessById(bmsDxGroupBuy.getBusinessId());
        bargainHelpPageRpDto.setBmsUserBargain(new BargainHelpPageRpDto.BmsUserBargainDto());
        BeanUtils.copyProperties(bmsUser,bargainHelpPageRpDto);
        BeanUtils.copyProperties(bmsDxGroupBuy,bargainHelpPageRpDto);
        BeanUtils.copyProperties(bmsUserBargain,bargainHelpPageRpDto.getBmsUserBargain());
        bargainHelpPageRpDto.getBmsUserBargain().setAlreadyBargainMoney(ArithUtil.sub(bmsUserBargain.getStartPrice(),bmsUserBargain.getFinallyPrice()));
        bargainHelpPageRpDto.setBargainId(bmsUserBargain.getId());
        bargainHelpPageRpDto.setUserHelpBargainList(helpBargains);
        bargainHelpPageRpDto.setHeadImg(bmsUser.getHeadImg());
        if(bmsUser.getSystemUser() != null && StringUtils.
                isNotBlank(bmsUser.getSystemUser().getHeadImgUrl())){
            bargainHelpPageRpDto.setHeadImg(bmsUser.getSystemUser().getHeadImgUrl());
        }
        bargainHelpPageRpDto.setLogoUrl(bmsBusiness.getLogoUrl());
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("count",helpBargainPage.getTotalElements());
        return ResultMapHelper.success(bargainHelpPageRpDto,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public synchronized Map<String, Object> userHelpBargain(ParamsMap paramsMap) {
        Date nowTime = new Date();
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer bargainId = paramsMap.getInteger("bargainId");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Optional<BmsUserBargain> bmsUserBargainOption = bmsUserBargainDao.findById(bargainId);
        if(!bmsUserBargainOption.isPresent()){
            return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_NO_EXIST);
        }
        BmsUserBargain bmsUserBargain = bmsUserBargainOption.get();
        if(bmsUserBargain.getProState() != CAN_BARGAIN_STATUS){
            return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_ALREADY_OVER);
        }
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyService.getGroupBuyById(bmsUserBargain.getGroupBuyId());
        //砍价订单
        Map<String,Object> retMap = this.startBargain(userId,bmsUserBargain.getSaasOrderId());
        if(!(retMap.containsKey("status") && (ResultCode.CODE_NORMAL.equals(retMap.get("status").toString())))){
            return retMap;
        }
        log.info("saas帮助砍价结果：" + JSON.toJSONString(retMap));
        Map<String,Object> resultData = (Map<String, Object>) retMap.get("data");
        Double cutPrice = Double.parseDouble(resultData.get("cutPrice").toString());
        Double startPrice = Double.parseDouble(resultData.get("startPrice").toString());
        Double nowPrice = Double.parseDouble(resultData.get("nowPrice").toString());
        String endTime = resultData.get("endTime").toString();
        String expireTime = resultData.get("expireTime").toString();
        bmsUserBargain.setStartPrice(startPrice);
        bmsUserBargain.setFinallyPrice(nowPrice);
        if(bmsUserBargain.getUserId().intValue() != userId.intValue()){
            bmsUserBargain.setFriendHelpNum((bmsUserBargain.getFriendHelpNum() == null ? 0 : bmsUserBargain.getFriendHelpNum()) + 1);
        }
        bmsUserBargain.setOverTime(DateTimeUtils.converStringToDate(endTime,DateTimeUtils.DATE_PATTERN_TIMESTAMP));
        bmsUserBargain.setExpireTime(DateTimeUtils.converStringToDate(expireTime,DateTimeUtils.DATE_PATTERN_TIMESTAMP));
        if(DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsUserBargain.getOverTime())
                && DateTimeUtils.converDateToInterger(nowTime) < DateTimeUtils.converDateToInterger(bmsUserBargain.getExpireTime())){
            bmsUserBargain.setProState(CAN_BUY_STATUS);
        }else if(DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsUserBargain.getExpireTime())){
            bmsUserBargain.setProState(EXPIRE_STATUS);
        }
        bmsUserBargainDao.save(bmsUserBargain);
        //同步插入一条砍价记录
        bmsUserHelpBargainService.addBargainRecord(userId,bmsUserBargain.getId(),cutPrice);
        Page<BmsUserHelpBargain> bmsUserHelpBargainPage = bmsUserHelpBargainService.getHelpRecord(bargainId,1,pageSize);
        BargainActionRpDto bargainActionRpDto = new BargainActionRpDto();
        bargainActionRpDto.setBargainPrice(Double.parseDouble(resultData.get("cutPrice").toString()));
        bargainActionRpDto.setGroupBuyId(bmsDxGroupBuy.getId());
        if(bmsUserHelpBargainPage.hasContent()) {
            bargainActionRpDto.setBmsUserHelpBargains(bmsUserHelpBargainPage.getContent());
        }
        if(bmsUserBargain.getUserId().intValue() == userId.intValue()){
            bargainActionRpDto.setIsBargainMy(Constants.COMMON_FLAG_TRUE_INT);
        }
        BmsUser bmsUser = TokenManager.getUser(bmsUserBargain.getUserId());
        if(bmsUser != null){
            bargainActionRpDto.setBargainUserName(BmsUserService.getLoginName(bmsUser));
        }
        BmsCommonService.getApplicationContext().publishEvent(new GroupBuyBargainEvent("countBargainNum",bmsUserBargain));
        return ResultMapHelper.success(bargainActionRpDto,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> getBargainHelpRecord(ParamsMap paramsMap) {
        Integer bargainId = paramsMap.getInteger("bargainId");
        Integer pageNum = paramsMap.getInteger("pageNum");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Optional<BmsUserBargain> bmsUserBargainOption = bmsUserBargainDao.findById(bargainId);
        if(!bmsUserBargainOption.isPresent()){
            return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_NO_EXIST);
        }
        Page<BmsUserHelpBargain> helpBargainPage = bmsUserHelpBargainService.getHelpRecord(bargainId,pageNum,pageSize);
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("count",helpBargainPage.getTotalElements());
        return ResultMapHelper.success(helpBargainPage.getContent(),userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> getAllActivity(ParamsMap paramsMap) {
        Integer nowTimestamp = DateTimeUtils.getNowTimeStamp();
        final int SHOW_ALL = -1;
        final int NO_PAY = 0;
        final int NO_USE = 1;
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Integer pageNum = paramsMap.getInteger("pageNum");
        Integer showStatus = paramsMap.getInteger("showStatus");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        if(showStatus == NO_PAY){
            conditionMap.put("status",BmsUserBargainService.NO_PAY_SATUS);
        }else if(showStatus == NO_USE){
            conditionMap.put("status",BmsUserBargainService.PAY_STATUS);
        }
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"newTime");
        Page<BmsUserBargain> bmsUserBargains = bmsUserBargainDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsUserBargain> bmsUserBargainList = bmsUserBargains.getContent();
        if(bmsUserBargainList != null && bmsUserBargainList.size() > 0){
            Set<Integer> groupBuyIds = bmsUserBargainList.stream().map(BmsUserBargain::getGroupBuyId).collect(Collectors.toSet());
            if(groupBuyIds.size() > 0){
                Map<Integer,BmsDxGroupBuy> bmsDxGroupBuyMap = bmsDxGroupBuyService.getGroupBuyById(groupBuyIds);
                for(BmsUserBargain bmsUserBargain : bmsUserBargainList){
                    if(bmsDxGroupBuyMap.containsKey(bmsUserBargain.getGroupBuyId())){
                        bmsUserBargain.setBmsDxGroupBuy(bmsDxGroupBuyMap.get(bmsUserBargain.getGroupBuyId()));
                    }
                    //处理过期
                    if(DateTimeUtils.converDateToInterger(DateTimeUtils.addDay(bmsUserBargain.getNewTime(),2)) <= nowTimestamp){
                        bmsUserBargain.setStatus(BmsUserBargainService.ALREADY_EXPIRE);
                    }
                    //处理砍价结束
                    /*if(DateTimeUtils.converDateToInterger(DateTimeUtils.addDay(bmsUserBargain.getNewTime(),1)) <= nowTimestamp){
                        bmsUserBargain.setIsOver(Constants.COMMON_FLAG_TRUE_INT);
                    }*/
                }
            }
            bmsUserBargainDao.saveAll(bmsUserBargainList);
        }
        Map<String,Object> userData = new HashMap<>();
        userData.put("count",bmsUserBargains.getTotalElements());
        return ResultMapHelper.success(bmsUserBargainList,userData,ResultMsg.MSG_GET_SUCCESS);
    }

    public void verBmsDxGroupBuy(Integer orderId) {
        BmsDxOrder bmsDxOrder = bmsDxOrderService.getBaseDao().findByIdAndIsDelete(orderId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxOrder != null && bmsDxOrder.getBargainId() != null){
            Optional<BmsUserBargain> bmsUserBargain = bmsUserBargainDao.findById(bmsDxOrder.getBargainId());
            if(bmsUserBargain.isPresent()){
                BmsUserBargain ba = bmsUserBargain.get();
                ba.setStatus(BmsUserBargainService.ALREADY_USE);
                ba.setVerifyTime(new Date());
                bmsUserBargainDao.save(ba);
            }
        }
    }

    @Override
    public Map<String, Object> share(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer bargainId = paramsMap.getInteger("bargainId");
        Optional<BmsUserBargain> bmsUserBargain = bmsUserBargainDao.findById(bargainId);
        if(!bmsUserBargain.isPresent()){
            return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_NO_EXIST);
        }
        BmsUserBargain bu = bmsUserBargain.get();
        Map<String,Object> rpcParams = new HashMap<>();
        rpcParams.put("orderId",bu.getSaasOrderId());
        String url = AppConfig.getProperty("saasGroupBuySys") + shareCuttingOrderUrl;
        url = RestTemplateUtils.getParamsUrl(url,rpcParams);
        String responseBody = RestTemplateUtils.postForEntityForJson(url,paramsMap);
        if(StringUtils.isNotBlank(responseBody)){
            Map<String,Object> retMap = JSON.parseObject(responseBody);
            if(!(retMap.containsKey("status") && (ResultCode.CODE_NORMAL.equals(retMap.get("status").toString())))){
                return retMap;
            }
            if(bu.getShareNum() == 0) {
                bu.setShareNum((bu.getShareNum() == null ? 0 : bu.getShareNum()) + 1);
            }
            bmsUserBargainDao.save(bu);
            ResultMapHelper.success(bmsUserBargain,ResultMsg.HAND_SUCCESS);
        }
        bmsUserBargainDao.save(bu);
        return ResultMapHelper.success(bmsUserBargain,ResultMsg.HAND_SUCCESS);
        //return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
    }

    @Override
    public Map<String, Object> getMyBargainGroupBuy(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer groupBuyId = paramsMap.getInteger("groupBuyId");
        Date nowTime = new Date();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("groupBuyId",groupBuyId);
        conditionMap.put("newTime_LTTE",nowTime);
        conditionMap.put("expireTime_GTT",nowTime);
        PersonBargainRecordRpDto personBargainRecordRpDto = new PersonBargainRecordRpDto();
        personBargainRecordRpDto.setServerTime(nowTime);
        List<BmsUserBargain> bmsUserBargains = bmsUserBargainDao.findAll(new SpecificationUtils(conditionMap));
        if(bmsUserBargains != null && bmsUserBargains.size() > 0){
            BmsUserBargain bmsUserBargain = bmsUserBargains.get(0);
            if(DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsUserBargain.getOverTime())
                    && DateTimeUtils.converDateToInterger(nowTime) < DateTimeUtils.converDateToInterger(bmsUserBargain.getExpireTime())){
                bmsUserBargain.setProState(CAN_BUY_STATUS);
            }else if(DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsUserBargain.getExpireTime())){
                bmsUserBargain.setProState(EXPIRE_STATUS);
            }
            /*if(DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsUserBargain.getOverTime())) {
                bmsUserBargain.setProState(EXPIRE_STATUS);
            }*/
            bmsUserBargainDao.save(bmsUserBargain);
            BeanUtils.copyProperties(bmsUserBargain,personBargainRecordRpDto);
            personBargainRecordRpDto.setBargainId(bmsUserBargain.getId());
            return ResultMapHelper.success(personBargainRecordRpDto,ResultMsg.MSG_GET_SUCCESS);
        }
        return ResultMapHelper.success(null,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Integer getBargainHelpNum(Integer bargainId) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userBargainId",bargainId);
        return (int) bmsUserHelpBargainService.getBaseDao().count(new SpecificationUtils(conditionMap));
    }

    @Override
    public void orderPay(String saasOrderId) {
        String url = AppConfig.getProperty("saasGroupBuySys") + payCuttingOrderUrl;
        Map<String,Object> rpcParams = new HashMap<>();
        rpcParams.put("orderId",saasOrderId);
        url = RestTemplateUtils.getParamsUrl(url,rpcParams);
        String responseBody = RestTemplateUtils.postForEntityForJson(url,rpcParams);
        log.info("saas pay result : " + responseBody);
        /*if(StringUtils.isNotBlank(responseBody)){
            Map<String,Object> retMap = JSON.parseObject(responseBody);
            if(retMap.containsKey("status") && (ResultCode.CODE_NORMAL.equals(retMap.get("status").toString()))){
                return true;
            }
        }
        return false;*/
    }

    @Override
    public void handleBackCardLogic(BmsUserBargain bmsUserBargain) {
        List<BmsUserHelpBargain> bmsUserHelpBargains = bmsUserHelpBargainService.getOtherHelpRecord(bmsUserBargain.getId(),bmsUserBargain.getUserId());
        if(bmsUserHelpBargains != null && bmsUserHelpBargains.size() > 0){
            for(BmsUserHelpBargain bmsUserHelpBargain : bmsUserHelpBargains){
                bmsBackCardService.addMoneyByUserId(bmsUserHelpBargain.getUserId(),bmsUserHelpBargain.getCutPrice());
            }
        }
    }

    @Override
    public void orderCommit(String orderId) {
        String url = AppConfig.getProperty("saasGroupBuySys") + commitCuttingOrderUrl;
        Map<String,Object> rpcParams = new HashMap<>();
        rpcParams.put("orderId",orderId);
        url = RestTemplateUtils.getParamsUrl(url,rpcParams);
        String responseBody = RestTemplateUtils.postForEntityForJson(url,rpcParams);
        log.info("saas commit result : " + responseBody);
    }

    @Override
    public List<BmsUserBargain> getBargainByIdIn(Set<Integer> bargainIds) {
        return bmsUserBargainDao.findByIdIn(bargainIds);
    }

    @Override
    public Map<Integer, BmsUserBargain> getBargainByIdInMap(Set<Integer> bargainId) {
        Map<Integer,BmsUserBargain> bmsUserBargainMap = new HashMap<>();
        List<BmsUserBargain> bmsUserBargains = getBargainByIdIn(bargainId);
        if(bmsUserBargains != null && bmsUserBargains.size() > 0){
            for(BmsUserBargain bmsUserBargain : bmsUserBargains){
                bmsUserBargainMap.put(bmsUserBargain.getId(),bmsUserBargain);
            }
        }
        return bmsUserBargainMap;
    }
}
